package com.example.demo.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.system.entity.User;
import com.example.demo.system.mapper.UserMapper;
import com.example.demo.system.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author XinYiFan
 * @since 2023-04-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Map<String,Object> login(User user){
        //根据用户信息找到数据库对应信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername());
        wrapper.eq(User::getPassword,user.getPassword());
        User loginUser = this.baseMapper.selectOne(wrapper);
        //结果不为空，生成一个token，并将用户信息存入Redis
        if(loginUser != null){
            //String token = CreatJwt.getToken(loginUser);//jwt生成token
            String key = String.valueOf(UUID.randomUUID());
            loginUser.setPassword(null);//密码置空
            redisTemplate.opsForValue().set(key,loginUser,30, TimeUnit.MINUTES);//存入Redis
            Map<String,Object> data = new HashMap<>();
            data.put("token",key);
            return data;
        }

        return null;
    }

    @Override
    public Map<String,Object> getUserInfo(String token){
        // 根据token获取用户信息，redis
        Object obj = redisTemplate.opsForValue().get(token);
        if(obj != null){
            //先把obj转换成json格式，再调用parseObject方法转换成User对象的格式
            User loginUser = JSON.parseObject(JSON.toJSONString(obj),User.class);

            Map<String, Object> data = new HashMap<>();
            data.put("name",loginUser.getUsername());	//用户名
            data.put("avatar", loginUser.getAvatar());	//头像
            // 角色
            List<String> roleList = this.baseMapper.getRoleNameByUserID(loginUser.getId());
            data.put("roles",roleList);
            return data;
        }
        return null;

    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(token);
    }
}
